<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="样品光谱编号"
        prop="sampleSpectrumDfbNo"
        label-width="100px"
      >
        <el-input
          v-model="queryParams.sampleSpectrumDfbNo"
          placeholder="请输入样品光谱编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器编号" prop="instrumentNo">
        <el-input
          v-model="queryParams.instrumentNo"
          placeholder="请输入仪器编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input
          v-model="queryParams.instrumentName"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样人" prop="builderName">
        <el-input
          v-model="queryParams.builderName"
          placeholder="请输入采样人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样时间" prop="samplingTime">
        <el-date-picker
          clearable
          v-model="queryParams.samplingTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采样时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row  v-if="isRowVisible" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['spectrum:dfb_spectrum:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['spectrum:dfb_spectrum:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['spectrum:dfb_spectrum:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['spectrum:dfb_spectrum:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
    ref="zlbSpectrumTable"
      v-loading="loading"
      :data="dfb_spectrumList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="样品光谱编号"
        align="center"
        prop="sampleSpectrumDfbNo"
      />
      <el-table-column
        label="波长"
        align="center"
        prop="wavelength"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="仪器编号" align="center" prop="instrumentNo" />
      <el-table-column label="仪器名称" align="center" prop="instrumentName" />
      <!-- <el-table-column label="起始波长" align="center" prop="startWavelength" />
      <el-table-column label="结束波长" align="center" prop="endWavelength" /> -->
      <el-table-column
        label="采样时间"
        align="center"
        prop="samplingTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.samplingTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采样人" align="center" prop="builderName" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        v-if="isRowVisible"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['spectrum:dfb_spectrum:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['spectrum:dfb_spectrum:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 光谱上传组件 -->
    <spectrum-upload
      :visible.sync="showUploadModal"
      @save="onSpectrumDataSave"
    />

    <!-- 添加或修改干燥流化床车间样品光谱对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="400px" append-to-body>
      <div
        style="padding-left: 20px; padding-right: 20px; padding-bottom: 20px"
      >
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          style="width: 100%"
          @click="showUploadModal = true"
        >
          导入光谱
        </el-button>
      </div>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="padding-right: 20px"
      >
        <el-form-item label="波长" prop="wavelength">
          <el-input
            v-model="form.wavelength"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="departmentName">
          <el-select
            v-model="form.departmentName"
            size="small"
            placeholder="请选择部门"
            clearable
            @change="handleDepartmentChange"
          >
            <el-option
              v-for="item in options.departments"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪器编号" prop="instrumentNo">
          <el-input v-model="form.instrumentNo" placeholder="请输入仪器编号" />
        </el-form-item>
        <el-form-item label="仪器名称" prop="instrumentName">
          <el-input
            v-model="form.instrumentName"
            placeholder="请输入仪器名称"
          />
        </el-form-item>
        <el-form-item label="起始波长" prop="startWavelength">
          <el-input
            v-model="form.startWavelength"
            placeholder="请输入起始波长"
          />
        </el-form-item>
        <el-form-item label="结束波长" prop="endWavelength">
          <el-input v-model="form.endWavelength" placeholder="请输入结束波长" />
        </el-form-item>
        <el-form-item label="采样时间" prop="samplingTime">
          <el-date-picker
            clearable
            v-model="form.samplingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择采样时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采样人" prop="builderName">
          <el-input v-model="form.builderName" placeholder="请输入采样人" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 选择仪器编号对话框 -->
    <el-dialog
      title="选择仪器编号"
      :visible.sync="instrumentDialogVisible"
      width="80%"
    >
      <instrument-data
        ref="instrumentDataRef"
        :is-row-visible="false"
        @selection-change="handleRowSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseInstrument">确 定</el-button>
        <el-button @click="instrumentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDfb_spectrum,
  getDfb_spectrum,
  delDfb_spectrum,
  addDfb_spectrum,
  updateDfb_spectrum,
} from "@/api/spectrum/dfb_spectrum";
import { listData as listInstrument } from "@/api/instrument/data";
import { listDept } from "@/api/system/dept";
import SpectrumUpload from "@/views/tool/build/SpectrumUpload.vue";
import InstrumentData from "@/views/instrument/data/index.vue";

export default {
  name: "Dfb_spectrum",
  components: {
    InstrumentData,
    SpectrumUpload,
  },
  props: {
    isRowVisible: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      instrumentDialogVisible: false, // 是否显示选择仪器编号对话框
      options: {
        departments: [], // 部门列表
      },
      showUploadModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 干燥流化床车间样品光谱表格数据
      dfb_spectrumList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sampleSpectrumDfbNo: null,
        wavelength: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sampleSpectrumDfbNo: [
          { required: true, message: "样品光谱编号不能为空", trigger: "blur" },
        ],
        wavelength: [
          { required: true, message: "波长不能为空", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        instrumentId: [
          { required: true, message: "仪器id不能为空", trigger: "blur" },
        ],
        instrumentNo: [
          { required: true, message: "仪器编号不能为空", trigger: "blur" },
        ],
        instrumentName: [
          { required: true, message: "仪器名称不能为空", trigger: "blur" },
        ],
        startWavelength: [
          { required: true, message: "起始波长不能为空", trigger: "blur" },
        ],
        endWavelength: [
          { required: true, message: "结束波长不能为空", trigger: "blur" },
        ],
        samplingTime: [
          { required: true, message: "采样时间不能为空", trigger: "blur" },
        ],
        builderId: [
          { required: true, message: "采样人id不能为空", trigger: "blur" },
        ],
        builderName: [
          { required: true, message: "采样人不能为空", trigger: "blur" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        creatorId: [
          { required: true, message: "新增人id不能为空", trigger: "blur" },
        ],
        creator: [
          { required: true, message: "新增人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "新增时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getDepartments();
    this.getList();
  },
  methods: {
    chooseInstrument() {
      const selectedInstrument = this.selectedInstrumentData;
      if (selectedInstrument) {
        this.form.instrumentId = selectedInstrument.instrumentId;
        this.form.instrumentNo = selectedInstrument.instrumentNo;
        this.form.instrumentName = selectedInstrument.instrumentName;
        this.instrumentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个仪器");
      }
    },
    handleRowSelection(selection) {
      const tableRef = this.$refs.instrumentDataRef.$refs.instrumentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedInstrumentData = lastSelected;
      } else {
        this.selectedInstrumentData = selection[0] || null;
      }
      console.log("查看选中的仪器数据", this.selectedInstrumentData);
    },
    handleDepartmentChange(deptName) {
      const dept = this.options.departments.find(
        (dept) => dept.deptName === deptName
      );
      if (dept) {
        this.form.departmentId = dept.deptId;
      } else {
        this.$modal.msgError("部门不存在");
        this.form.departmentId = null;
      }
    },
    async getDepartments() {
      try {
        const response = await listDept(); // 替换为实际的部门列表API
        this.options.departments = response.data;
        console.log("获取部门列表成功:", response.data);
      } catch (error) {
        console.error("获取部门列表失败:", error);
      }
    },
    async onSpectrumDataSave(data) {
      console.log("收到光谱数据:", data);
      // 这里可以处理 form 赋值、请求 setInstrumentInfo 等逻辑
      this.form.instrumentNo = data.spectrometerModel;
      this.form.wavelength = data.absorbanceString;
      this.form.samplingTime = data.samplingTime;

      // 根据光谱仪型号查询并赋值 ID
      try {
        const response = await listInstrument({
          instrumentName: data.spectrometerModel,
        });
        if (response.code === 200 && response.rows?.length > 0) {
          const ins = response.rows[0];
          this.form.instrumentId = ins.instrumentId;
          this.form.instrumentNo = ins.instrumentNo;
          this.form.instrumentName = ins.instrumentName;
        } else {
          this.$message.error("仪器不存在，请前往仪器管理添加！");
        }
      } catch (err) {
        this.$message.error("获取仪器信息失败: " + err.message);
      }

      // 解析波长范围
      if (data.wavelengthRange) {
        const [start, end] = data.wavelengthRange
          .split("--")
          .map((v) => parseFloat(v));
        this.form.startWavelength = start;
        this.form.endWavelength = end;
      }

      this.$message.success("数据导入成功");
    },
    /** 查询干燥流化床车间样品光谱列表 */
    getList() {
      this.loading = true;
      listDfb_spectrum(this.queryParams).then((response) => {
        this.dfb_spectrumList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sampleSpectrumDfbId: null,
        sampleSpectrumDfbNo: null,
        wavelength: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        startWavelength: null,
        endWavelength: null,
        samplingTime: null,
        builderId: null,
        builderName: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        createTime: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.sampleSpectrumDfbId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.$emit("selection-change", selection);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加干燥流化床车间样品光谱";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sampleSpectrumDfbId = row.sampleSpectrumDfbId || this.ids;
      getDfb_spectrum(sampleSpectrumDfbId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改干燥流化床车间样品光谱";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.sampleSpectrumDfbId != null) {
            updateDfb_spectrum(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDfb_spectrum(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sampleSpectrumDfbIds = row.sampleSpectrumDfbId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除干燥流化床车间样品光谱编号为"' +
            sampleSpectrumDfbIds +
            '"的数据项？'
        )
        .then(function () {
          return delDfb_spectrum(sampleSpectrumDfbIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "spectrum/dfb_spectrum/export",
        {
          ...this.queryParams,
        },
        `dfb_spectrum_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.drawer-footer {
  /* width: 100%; */
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>
